<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btnList="fullInfo.btnList"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>
              {{ $t('basic_information') }}
            </p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="setRules()"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
              @handleEvent="handleEvent"
            >
              <template v-slot:form-validity>
                <div class="flex">
                  <el-input-number
                    style="width: 65%"
                    controls-position="right"
                    :min="0"
                    placeholder="请输入内容"
                    v-model="formInfo.data.validity"
                    type="number"
                    class="flex-input"
                  >
                  </el-input-number>
                  <selectModel
                    v-model="formInfo.data.validityUnit"
                    type-code="validity_unit"
                    :clearable="false"
                    style="width: 35%"
                    class="flex-select"
                  />
                </div>
              </template>
              <!-- 自定义插槽-选择证照 -->
              <template v-slot:form-licenseFilePath>
                <div class="slot-licenseFilePath">
                  <UploadImg
                    v-model:value="formInfo.data.licenseFilePathList"
                    multiple
                    :action="action"
                    :title="$t('license')"
                    :responseFn="handleResponse"
                    :limit="
                      $store.state.permission.systemConfig.max_upload_picture
                        ? $store.state.permission.systemConfig
                            .max_upload_picture
                        : 2
                    "
                  />
                </div>
              </template>
              <template v-slot:form-licenseEndDate>
                <el-date-picker
                  v-if="$store.state.permission.systemConfig.is_check_license_end_time == 1"
                  v-model="formInfo.data.licenseEndDate"
                  type="date"
                  :value-format="'YYYY-MM-DD'"
                  placeholder="请选择证照失效日期"
                  :disabled-date="TimePickerOptions.disabledDate"
                  clearable
                />
                <el-date-picker
                  v-else
                  v-model="formInfo.data.licenseEndDate"
                  type="date"
                  :value-format="'YYYY-MM-DD'"
                  placeholder="请选择证照失效日期"
                  clearable
                />
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel" v-if="islicenseApplicationType">
          <div class="model-panel-title">
            <p>关联产品信息</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <NewPageFilter
              v-model:query="filterInfo.query"
              :filter-btn="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button
                  :disabled="id ? formInfo.data.status === 0 : false"
                  @click="addProduct()"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="
                    !tableInfo.selections.length ||
                    (id ? formInfo.data.status === 0 : false)
                  "
                  @click="removeProduct"
                  >删除产品</el-button
                >
              </template>
            </NewPageFilter>
            <div class="flex_full_item">
              <PageTable
                v-model:data="tableInfo.data"
                :pager="false"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEventTable"
              >
                <template #col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template #col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
                <template #col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template #col-supplierName="scope">
                  <p>{{ scope.row.supplierName || '-' }}</p>
                </template>
                <template #col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
              </PageTable>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <selectProduct
      v-if="productInfo.visible"
      v-model:showDialog="productInfo.visible"
      v-model:query="productInfo.query"
      :query="productInfo.query"
      :tableKey="productInfo.tableKey"
      :showPrice="$permission('purchSubscribeTemplate:price')"
      @callback="_selectProduct"
    />
  </div>
</template>

<script setup name="licenseModify">
import {
  createLicense,
  getBrandAll,
  selectLicenseDetail,
  updateLicense,
  getProductPage,
  deleteRelationProduct,
} from '@/api/core'
import selectProduct from './selectProduct.vue'
import axios from 'axios'

const emit = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  licenseId: {
    type: String || Number,
    default: '',
  },
  id: {
    type: String || Number,
    default: '',
  },
  type: {
    type: String,
    default: '',
  },
})

const action = axios.defaults.baseURL + '/pub/uploadfile'
const licenseTypeChange = ref(false)
const licenseNumChange = ref(false)
const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})

//选择产品相关
const productInfo = ref({
  api: getProductPage,
  visible: false,
  tableKey: 'productProductList-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    idNotIn: '',
  },
})

// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})

// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      minWidth: 220,
      maxlength: 200,
      type: 'slot',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      minWidth: 150,
      type: 'slot',
    },
    { label: '助记符', value: 'mnemonic', width: '100px' },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      minWidth: 220,
      type: 'slot',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
        ifRender: ifRenderBack,
      },
    ],
  },
})
const TimePickerOptions = {
  disabledDate(time) {
    return time.getTime() < Date.now()
  },
}
// 表单相关
const formInfo = ref({
  ref: null,
  data: {
    manageType: 1,
    licenseNumber: '',
    licenseType: 0,
    status: 1,
  },
  fieldList: [
    {
      label: '证照类型',
      value: 'licenseType', //0备案证，1注册，2非医疗, 3消字
      type: 'select-model',
      code: 'license_type',
      event: 'licenseType',
      checkDefault: false,
    },
    {
      label: '证照分类',
      value: 'licenseApplicationType', //1耗材，2设备
      type: 'select-model',
      code: 'license_application_type',
    },
    {
      label: '证号',
      value: 'licenseNumber',
      type: 'input',
      maxlength: 30,
    },
    {
      label: '管理类别', //1第一类，2第二类，3第三类
      value: 'manageType',
      type: 'select-model',
      show: true,
      optionDisabled: [],
      disabled: true,
      code: 'license_manage_type',
    },
    {
      label: '产品名称',
      value: 'licenseName',
      type: 'input',
      maxlength: 200,
    },
    {
      label: '英文名称',
      value: 'enName',
      type: 'input',
      maxlength: 128,
      maxlength: 200,
    },
    {
      label: '证照生效日期',
      value: 'licenseBeginDate',
      type: 'date',
      dateType: 'date',
    },
    {
      label: '证照失效日期',
      value: 'licenseEndDate',
      type: 'slot',
    },
    {
      label: '生产厂家',
      value: 'brand',
      type: 'select',
      list: 'brandList',
      filterable: true,
    },
    {
      label: '包装规格',
      value: 'packedStandard',
      type: 'input',
      maxlength: 2000,
    },
    {
      label: '产品有效期',
      value: 'validity',
      type: 'slot',
      max: 30000,
    },
    // {
    //   label: "有效期单位",
    //   value: "validityUnit",
    //   type: "select-model",
    //   code: "validity_unit"
    // },
    {
      label: '生产地址',
      value: 'productionAddress',
      type: 'input',
      maxlength: 128,
    },
    {
      label: '预计用途',
      value: 'expectedUse',
      type: 'input',
      maxlength: 128,
    },
    {
      label: '存储条件',
      value: 'storageCondition',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'enabled_type',
      show: proxy.$permission('license:enabled'),
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 2000,
    },
    {
      label: '证照',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  recordRules: {
    //备案证
    licenseType: [
      { required: true, message: '请选择证照类型', trigger: 'change' },
    ],
    licenseApplicationType: [
      { required: true, message: '请选择证照分类', trigger: 'change' },
    ],
    licenseNumber: [{ required: true, message: '请输入证号', trigger: 'blur' }],
    licenseName: [
      { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    brand: [{ required: true, message: '请选择生产厂家', trigger: 'change' }],
  },
  regcRules: {
    //注册证
    licenseType: [
      { required: true, message: '请选择证照类型', trigger: 'change' },
    ],
    licenseApplicationType: [
      { required: true, message: '请选择证照分类', trigger: 'change' },
    ],
    licenseNumber: [{ required: true, message: '请输入证号', trigger: 'blur' }],
    licenseName: [
      { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    brand: [{ required: true, message: '请选择生产厂家', trigger: 'change' }],

    licenseEndDate: [
      {
        required: true,
        message: '请选择证照失效日期',
        trigger: 'change',
      },
    ],
  },
  otherRules: {
    //非医疗耗材
    licenseType: [
      { required: true, message: '请选择证照类型', trigger: 'change' },
    ],
    licenseApplicationType: [
      { required: true, message: '请选择证照分类', trigger: 'change' },
    ],
    licenseNumber: [{ required: true, message: '请输入证号', trigger: 'blur' }],
    licenseName: [
      { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    brand: [{ required: true, message: '请选择生产厂家', trigger: 'change' }],
  },
  labelWidth: '120px',
})

// 相关列表
const listTypeInfo = reactive({
  brandList: [],
})

const islicenseApplicationType = computed(() => {
  return formInfo.value.data.licenseApplicationType == 1
})

watch(
  () => formInfo.value.data.licenseApplicationType,
  (val) => {
    tableInfo.value.data = []
    tableInfo.value.selections = []
    tableInfo.value.initCurpage = 1
  }
)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => formInfo.value.data.licenseType,
  (val) => {
    let licenseNumber = formInfo.value.data.licenseNumber
    // showFieldListItem(val == 0 || val == 1, 'licenseNumber')
    if (val == 0) {
      formInfo.value.data.manageType = 1
      disableFieldListItem(true, 'manageType')
      formInfo.value.fieldList[2].optionDisabled = []
    } else if (val == 1) {
      disableFieldListItem(false, 'manageType')
      formInfo.value.fieldList[2].optionDisabled = ['1']
      if (licenseTypeChange.value || !props.id) {
        if (!licenseNumber) {
          formInfo.value.data.manageType = ''
        } else {
          let valNumber = licenseNumber.replace(/[^0-9]/gi, '')
          if (valNumber && valNumber.length >= 9) {
            let str = valNumber.slice(8, 9)
            console.log(str)
            switch (str) {
              case '2':
                formInfo.value.data.manageType = 2
                break
              case '3':
                formInfo.value.data.manageType = 3
                break
              default:
                formInfo.value.data.manageType = ''
                break
            }
          } else {
            formInfo.value.data.manageType = ''
          }
        }
      }
    } else if (val == 2 || val == 3) {
      formInfo.value.data.manageType = ''
      disableFieldListItem(true, 'manageType')
    }
    licenseTypeChange.value = true
  }
)
watch(
  () => formInfo.value.data.licenseNumber,
  (val) => {
    let licenseType = formInfo.value.data.licenseType
    if (licenseType == 1) {
      if (licenseNumChange.value || !props.id) {
        if (!val) {
          formInfo.value.data.manageType = ''
        } else {
          let valNumber = val.replace(/[^0-9]/gi, '')
          if (valNumber && valNumber.length >= 9) {
            let str = valNumber.slice(8, 9)
            switch (str) {
              case '2':
                formInfo.value.data.manageType = 2
                break
              case '3':
                formInfo.value.data.manageType = 3
                break
              default:
                formInfo.value.data.manageType = ''
                break
            }
          } else {
            formInfo.value.data.manageType = ''
          }
        }
      }
    }
    licenseNumChange.value = true
  }
)
onMounted(() => {
  getBrandList()
  if (props.id) {
    getDetails()
  } else {
    formInfo.value.data.licenseType = 0
  }
})
function ifRenderBack() {
  return props.id ? formInfo.value.data.status === 0 : false
}
function addProduct() {
  const idNotIn = []
  tableInfo.value.data.map((item) => {
    idNotIn.push(item.id)
  })
  productInfo.value.query.idNotIn = idNotIn.join(',')
  productInfo.value.visible = true
}
function handleEventTable(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    if (props.id) {
      deleteRelationProduct([selectRow.id], props.id).then((res) => {
        if (res && res.success) {
          tableInfo.value.data = tableInfo.value.data.filter(
            (row) => row !== selectRow
          )
          proxy.$message({
            message: `操作成功`,
            type: 'success',
          })
        }
      })
    } else {
      tableInfo.value.data = tableInfo.value.data.filter(
        (row) => row !== selectRow
      )
    }
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let ids = []
        tableInfo.value.selections.map((i) => {
          ids.push(i.id)
        })
        if (props.id) {
          deleteRelationProduct(ids, props.id).then((res) => {
            if (res && res.success) {
              tableInfo.value.data = tableInfo.value.data.filter(
                (row) => !tableInfo.value.selections.includes(row)
              )
              proxy.$message({
                message: `操作成功`,
                type: 'success',
              })
            }
          })
        } else {
          tableInfo.value.data = tableInfo.value.data.filter(
            (row) => !tableInfo.value.selections.includes(row)
          )
        }
      })
  }
}

//选择产品
function _selectProduct(rows) {
  if (rows) {
    const data = rows.map(function (item) {
      return {
        ...item,
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}

function handleEvent(str, value) {
  if (str === 'licenseType') {
    formInfo.value.data.licenseType = value
  }
}
function showFieldListItem(show, nameValue) {
  let fieldList = proxy.$fn.deepClone(formInfo.value.fieldList)
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
  formInfo.value.fieldList = fieldList
}
function disableFieldListItem(disabled, nameValue) {
  let fieldList = formInfo.value.fieldList
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.disabled = disabled
    }
  })
}
function setRules() {
  // proxy.$nextTick(() => {
  //   formInfo.value.ref.clearValidate()
  // })
  if (formInfo.value.data.licenseType == 0) {
    return formInfo.value.recordRules
  } else if (formInfo.value.data.licenseType == 1) {
    return formInfo.value.regcRules
  } else if (formInfo.value.data.licenseType == 2 || formInfo.value.data.licenseType == 3) {
    return formInfo.value.otherRules
  }
}
function handleResponse(response) {
  return response
}
//获取厂家列表
function getBrandList() {
  let params = {
    status: '1',
  }
  getBrandAll(params).then((resp) => {
    if (resp && resp.success) {
      listTypeInfo.brandList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      if (
        formInfo.value.data.licenseEndDate &&
        formInfo.value.data.licenseBeginDate &&
        formInfo.value.data.licenseEndDate <
          formInfo.value.data.licenseBeginDate
      ) {
        proxy.$message({
          message: '证照失效日期不能小于证照生效日期',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
      if (proxy.$store.state.permission.systemConfig.is_check_license_end_time == 1 && (new Date(formInfo.value.data.licenseEndDate) <= Date.now())) {
        proxy.$message({
          message: '证照失效日期必须要大于当前日期',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
      let api
      formInfo.value.data.licenseFilePath =
        formInfo.value.data.licenseFilePathList &&
        formInfo.value.data.licenseFilePathList.length > 0
          ? formInfo.value.data.licenseFilePathList.join(',')
          : ''
      let productIds = []
      tableInfo.value.data.map((item) => {
        productIds.push(item.id)
      })
      const params = {
        ...formInfo.value.data,
        productIds: productIds,
        licenseType: Number(formInfo.value.data.licenseType)
      }
      const type = props.type
      if (type === 'create') {
        api = createLicense
      } else if (type === 'update') {
        api = updateLicense
      } else {
        return
      }
      proxy.$handleAPI(type, api, params).then((res) => {
        if (res.success) {
          showDialog.value = false
          emit('returnModify', false)
        }
      })
      // .catch(e => {
      // })
    }
  })
}
async function getDetails() {
  await selectLicenseDetail(props.id).then((resp) => {
    if (resp && resp.success) {
      if (resp.data.manageType == -2) {
        resp.data.manageType = ''
      }
      formInfo.value.data = resp.data
    }
  })
  await getProductPage({ licenseId: props.id || null }).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.data = data
    }
  })
}
function getProduct() {
  getProductPage({ licenseId: props.id || null }).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.data = data
    }
  })
}
</script>

<style scoped>
.flex {
  display: flex;
  flex: 1;
}
.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
</style>
